import {defineStore} from "pinia";
import {computed, ref} from "vue";
import type {Admin, adminData} from "@/types/auth.ts";
import type {LoginResponseData, Menu, ApiResponse} from "@/types/base.ts";
import {ElMessage} from "element-plus";
import request from "@/utils/request.ts";
import {BusinessCode} from "@/utils/businessCode.ts";
import {MenuFilter} from "@/utils/menuFilter.ts";
import router from "@/router";
// import { MenuFilter } from "@/utils/menuFilter0.ts";

export const useAuthStore = defineStore('auth', () => {
    // ============ State ============
    const token = ref<string>(localStorage.getItem('token') || '');
    const admin = ref<Admin | null>(parseJSON<Admin>(localStorage.getItem('admin')));
    const menuTree = ref<Menu[]>(parseJSON<Menu[]>(localStorage.getItem('menuTree')) || []);
    const myMenus = ref<Menu[]>(parseJSON<Menu[]>(localStorage.getItem('myMenus')) || []);
    const allowedMenuIds = ref<number[]>(parseJSON<number[]>(localStorage.getItem('allowedMenuIds')) || []);
    const permsList = ref<string[]>(parseJSON<string[]>(localStorage.getItem('permsList')) || []);

    // ============ Getters ============
    // 计算属性
    const isLogin = computed(() => !!token.value);
    const username = computed(() => admin.value?.username);

    // ============ Actions ============
    // 设置token
    const setToken = (newToken: string) => {
        token.value = newToken;
        newToken ? localStorage.setItem('token', newToken) : localStorage.removeItem('token');
    };

    // 设置管理员信息
    const setAdmin = (newAdmin: Admin | null) => {
        admin.value = newAdmin;
        newAdmin ? localStorage.setItem('admin', JSON.stringify(newAdmin)) : localStorage.removeItem('admin');
    };

    const setMyMenus = (newMyMenus: Menu[] | null) => {
        console.log("newMyMenus");
        myMenus.value = newMyMenus || [];
        newMyMenus ? localStorage.setItem('myMenus', JSON.stringify(newMyMenus)) : localStorage.removeItem('myMenus');
    };

    const setAllowedMenuIds = (newAllowedMenuIds: number[] | null) => {
        allowedMenuIds.value = newAllowedMenuIds || [];
        newAllowedMenuIds ? localStorage.setItem('allowedMenuIds', JSON.stringify(newAllowedMenuIds)) : localStorage.removeItem('allowedMenuIds');
    };

    const setMenuTree = (newMenuTree: Menu[] | null) => {
        menuTree.value = newMenuTree || [];
        newMenuTree ? localStorage.setItem('menuTree', JSON.stringify(newMenuTree)) : localStorage.removeItem('menuTree');
    };

    const setPermsList = (newPermsList: string[] | null) => {
        permsList.value = newPermsList || [];
        newPermsList ? localStorage.setItem('permsList', JSON.stringify(newPermsList)) : localStorage.removeItem('permsList');
    };

    // 登录逻辑
    const login = async (adminData: adminData) => {
        try {
            const res = await request.post<LoginResponseData>('/common/login', adminData);
            console.log("登录接口返回的原始数据：", res.data);
            if (res.data.code === BusinessCode.SUCCESS.code) {
                const { token, admin, allowedMenuIds, menuTree, permsList } = res.data!;
                console.log("登录接口返回的原始数据：", { allowedMenuIds, menuTree });
                setToken(token);
                setAdmin(admin);
                setAllowedMenuIds(allowedMenuIds);
                setMenuTree(menuTree);
                setPermsList(permsList);
                // const filteredMenus = MenuFilter.use('recursive').filter(res.data.menuTree, res.data.allowedMenuIds);
                const filteredMenus = MenuFilter.use('recursive').filter(
                    menuTree,
                    allowedMenuIds.map(id => String(id)) // id 类型为 number，无 any 错误
                );
                setMyMenus(filteredMenus || null);
                return { success: true };
            } else if (res.data.code === BusinessCode.CAPTCHA_INCORRECT.code) {
                ElMessage.error("验证码不正确");
                return { success: false };
            } else {
                ElMessage.error("用户名密码不正确");
                return { success: false };
            }
        } catch (error) {
            ElMessage.error("请求出错，请重试");
            return { success: false };
        }
    };

    // 退出逻辑
    const logout = async () => {
        try {
            await request.get('/logout'); // 即使接口失败也清除本地数据
        } finally {
            setToken('');
            setAdmin(null);
            setAllowedMenuIds(null);
            setPermsList(null);
            setMenuTree(null);
            setMyMenus(null);
            router.push('/login');
        }
        return { success: true };
    };

    // ============ 返回 Store ============
    // 正确返回所有属性和方法（之前嵌套错误导致此处未执行）
    return {
        token, admin, allowedMenuIds, permsList, menuTree, myMenus,
        isLogin, username,
        setToken, setAdmin, setMyMenus, setAllowedMenuIds, setMenuTree, setPermsList,
        login, logout
    };
});

// ============ 工具函数：安全解析 JSON ============
function parseJSON<T>(str: string | null): T | null {
    if (!str) return null;
    try {
        return JSON.parse(str) as T;
    } catch {
        console.warn('Invalid JSON in localStorage:', str);
        return null;
    }
}
